package com.scalar.chiptrack.adaptor.msilica;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import java.io.BufferedInputStream;
import java.net.URL;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;


/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 19 Jul, 2010
 * Time: 10:59:01 AM
 * To change this template use File | Settings | File Templates.
 */
public class ANSTAdaptor extends JobHandler implements AdaptorConstants
{
    private static final int PORT                       = 80;
    private static final String URL                     = "http://58.214.5.226:8081/";
    private static final String POST_URI_LOGIN          = "AnstCustomers/login.do";
    private static final String DOWNLAOD_FILE_URI       = "AnstCustomers/MSI.do?method=queryMSIAllWIP";

    public static final String FILE_NAME_WIP            = "ANST_ALL_WIP";
	public static final String ADAPTOR_NAME             = "ANST_WIP";

    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;
    private String m_password           = null;
    private int    m_adaptor_id     = -1;

    public ANSTAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_ANST, LOCATION_TYPE_ASSEMBLY );

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_ANST );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading ANST Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading ANST Adaptor Username, Password details from database" );
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new ANSTAdaptor().execute();
    }

    public void execute() throws Exception
    {
        m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
        //Print the header details
        AdaptorUtils.printHeader(VENDOR_NAME_ANST, CONSTANT_ADAPTOR);

        AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

        HTTPConnection connection = login( URL  );

        if ( connection != null )
        {
            BufferedInputStream bfReader = null;
            try
            {
                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipStatusReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the All Wip Sheet..." );
                        log( "\tDownloading the All Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP , FILE_EXTN_XLS,true );

                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save All Wip Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save All Wip Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of All Wip Sheet" );
                    throw new ScalarException( "Could not create response object of All Wip Sheet" );
                }

                // Logging out from ANST WEB SITE
                //logout( connection );
                 bfReader = null;
            }
            finally
            {
                 if ( bfReader != null )
                 {
                     bfReader.close();
                     bfReader = null;
                 }
            }

        }
        else
        {
            log( "Could not able to get the Connection to web site" );
            throw new ScalarException( "Could not able to get the Connection to web site" );
        }
    }

    /**
     *
     * @param url
     * @return
     * @throws Exception
     */

    private HTTPConnection login( String url ) throws Exception
    {
        byte[] data         = new byte[1024];

        URL connUrl = new URL(url);
        HTTPConnection conn = new HTTPConnection(connUrl);

        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

        HTTPResponse rsp = conn.Get( "AnstCustomers/" );

        System.out.print( "Trying to Logging in......" );
        log( "Trying to Logging in......" );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/

        NVPair[] formData = new NVPair[ 2 ];
        formData[ 0 ] = new NVPair( "username", m_username );
        formData[ 1 ] = new NVPair( "password", m_password );

        rsp  = conn.Get( POST_URI_LOGIN, formData );
        //System.out.println("rsp.getEffectiveURI() = " + rsp.getEffectiveURI());

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/

       log( "Response from Server: " + rsp.getStatusCode() + " " + rsp.getReasonLine() );

        if ( rsp.getStatusCode() >= 400 )
        {
            System.out.println( "Login failed.. response from server: " + rsp.getStatusCode() );
            log( "Login failed.. response from server: " + rsp.getStatusCode() );
            conn = null;
        }

        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipStatusReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse   rsp  = null;

        System.out.println( "\nSubmitting the request for Wip Info......" );
        log( "Submitting the request for  Wip Info......" );

        rsp = conn.Get( DOWNLAOD_FILE_URI ) ;
        System.out.println("rsp.getEffectiveURI() = " + rsp.getEffectiveURI());        
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/

        return rsp;
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

